package com.g13.virtualpethospital.controller;
import com.g13.virtualpethospital.common.Result;
import com.g13.virtualpethospital.entity.QuestionEntity;
import com.g13.virtualpethospital.entity.base.AnswerResult;
import com.g13.virtualpethospital.entity.TestPaperBriefEntity;
import com.g13.virtualpethospital.entity.TestPaperEntity;
import com.g13.virtualpethospital.controller.request.UploadAnswerRequest;
import com.g13.virtualpethospital.controller.response.UploadAnswerResponse;
import com.g13.virtualpethospital.exceptions.TestPaperException;
import com.g13.virtualpethospital.service.QuestionService;
import com.g13.virtualpethospital.service.TestExamService;
import com.g13.virtualpethospital.service.TestPaperService;
import io.swagger.annotations.*;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Title: TestPaperController
 * @Author chilly
 * @Package com.g13.virtualpethospital.controller
 * @Date 2024/3/25 15:14
 * @description: 试卷相关
 */
@Slf4j
@RestController
@ApiModel("试卷操作相关接口")
@RequestMapping("/paper")
public class TestPaperController {

    @Autowired
    private TestPaperService testPaperService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private TestExamService testExamService;


    /**
     * 添加考卷
     * @return
     */
    @PostMapping("/addPaper")
    @ApiOperation("添加试卷")

    public Result<Integer> addTestPaper(@RequestBody TestPaperBriefEntity testPaperBriefEntity) {
        TestPaperBriefEntity addtestPaperBriefEntity = new TestPaperBriefEntity();
        addtestPaperBriefEntity.setQuestions(testPaperBriefEntity.getQuestions());
        addtestPaperBriefEntity.setHeadline(testPaperBriefEntity.getHeadline());
        addtestPaperBriefEntity.setTime(testPaperBriefEntity.getTime());

        String[] questions = testPaperBriefEntity.getQuestions();
        int totalQuestions = questions.length;
        long totalScoref = totalQuestions * 5;

        addtestPaperBriefEntity.setTotalScore(totalScoref);
        if (addtestPaperBriefEntity.getHeadline().trim() == "" || addtestPaperBriefEntity.getTotalScore() == 0 || addtestPaperBriefEntity.getTime() == 0 || addtestPaperBriefEntity.getQuestions() == null)
            return Result.fail("试卷输入不能为空或全为不可见字符");
        else {
            try {
                testPaperService.addTestPaper(addtestPaperBriefEntity);
                return Result.success("添加成功", null);
            } catch (Exception e) {
                return Result.fail("添加失败" + e.getMessage());
            }
        }
    }

    /**
     * 删除考卷
     * @param paperId
     * @return
     */
    @DeleteMapping("/deletePaper")
    @ApiOperation("删除试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperId", value = "试卷编号", required = true, paramType = "query", dataType = "String")})
    public Result<Integer> deleteTestPaper(@NonNull @RequestParam("paperId")  String paperId) {
        try {
                testPaperService.deleteTestPaper(paperId);
                return Result.success("删除成功", null);
        } catch (TestPaperException e) {
            return Result.fail("试卷不存在，删除失败");
        }
    }


    /**
     * 更新试卷
     * @param testPaperBriefEntity
     * @return
     */

//    (@NonNull @RequestParam("paperId") String paperId,@NonNull @RequestParam("headline") String headline,@NonNull @RequestParam("time") long time,
//    @NonNull @RequestParam("totalScore") long totalScore,@NonNull @RequestParam("questions") List<String>)
    @PutMapping("/modifyPaper")
    @ApiOperation("修改更新试卷")
    public Result<TestPaperBriefEntity> updateTestPaper(@NonNull @RequestBody TestPaperBriefEntity testPaperBriefEntity) {

        if (testPaperBriefEntity.getHeadline().trim() == "" || testPaperBriefEntity.getQuestions() == null)
            return Result.fail("试卷输入不能为空或全为不可见字符");
        else if(testPaperBriefEntity.getTime() == 0){
            return Result.fail("考试时间不能为0或为空");
        }
        else {
            try {
                String[] questions = testPaperBriefEntity.getQuestions();
                int totalQuestions = questions.length;
                long totalScoref = totalQuestions * 5;
                testPaperBriefEntity.setTotalScore(totalScoref);
                testPaperService.updateTestPaper(testPaperBriefEntity, testPaperBriefEntity.getPaperId());
                return Result.success("更新成功", testPaperBriefEntity);
            } catch (Exception e) {
                return Result.fail("修改失败:" + e.getMessage());
            }
        }
    }


    /**
     * 按照标题查找试卷，留空则视为不做筛选
     * @param headline
     * @return
     */

    @GetMapping("/getPaperByHeadline")
    @ApiOperation("按照标题查询试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "headline", value = "试卷标题", required = false, paramType = "query", dataType = "String")})
    public Result<List<TestPaperBriefEntity>> findTestPaperByHeadline(@RequestParam(value = "headline", required = false) String headline) {
        try {
            List<TestPaperBriefEntity> res;
            if (headline == null || headline.isEmpty()) {
                res = testPaperService.findAllTestPaper();
            } else {
                res = testPaperService.findTestPaperByHeadline(headline);
            }
            if (res != null && !res.isEmpty()) {
                return Result.success("查询成功", res);
            } else {
                return Result.fail("试卷不存在", Collections.emptyList());
            }
        }catch (Exception e){
            return Result.fail("操作失败" + e.getMessage(),null);
        }
    }

    /**
     * 查询所有试卷
     * @return
     */
    @GetMapping("/getAllPaper")
    @ApiOperation("查询所有试卷")
    public Result<List<TestPaperBriefEntity>> findAllTestPaper() {
        try {
            List<TestPaperBriefEntity> res =  testPaperService.findAllTestPaper();
            if (res != null && !res.isEmpty()) {
                return Result.success("查询成功", res);
            } else {
                return Result.fail("没有找到试卷", Collections.emptyList());
            }
        } catch (Exception e) {
            return Result.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 按照Id查询试卷
     * @param paperId
     * @return
     */
    @GetMapping("/getPaperById")
    @ApiOperation("按照Id查询试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperId", value = "试卷编号", required = true, paramType = "query", dataType = "String")})
    public Result<List<TestPaperBriefEntity>> findTestPaperById(@NonNull @RequestParam("paperId") String paperId) {
        try {
            List<TestPaperBriefEntity> res =  testPaperService.findTestPaperById(paperId);
            if (res != null) {
                return Result.success("查询成功", res);
            } else {
                return Result.fail("试卷不存在", null);
            }
        } catch (Exception e) {
            return Result.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 选择试卷
     * @param paperId
     * @return
     */
    @GetMapping("/choosePaper")
    @ApiOperation("选择试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperId", value = "试卷编号", required = true, paramType = "query", dataType = "String")
    })
    public Result<TestPaperEntity> choosePaper(@NonNull @RequestParam("paperId") String paperId) {
        try {
            List<TestPaperBriefEntity> resList = testPaperService.findTestPaperById(paperId);
            if (!resList.isEmpty()) {
                TestPaperBriefEntity res = resList.get(0);
                TestPaperEntity testPaperEntity = new TestPaperEntity();
                testPaperEntity.setHeadline(res.getHeadline());
                testPaperEntity.setPaperId(res.getPaperId());
                testPaperEntity.setTotalScore(res.getTotalScore());
                testPaperEntity.setTime(res.getTime());
                testPaperEntity.setScores(res.getScores());

                List<QuestionEntity> questions = new ArrayList<>();
                for (String questionId : res.getQuestions()) {
                    QuestionEntity questionEntity = questionService.findQuestionById(questionId);
                    questions.add(questionEntity);
                }
                testPaperEntity.setQuestions(questions.toArray(new QuestionEntity[0]));

                return Result.success("选择试卷成功", testPaperEntity);
            } else {
                return Result.fail("试卷不存在", null);
            }
        } catch (Exception e) {
            return Result.fail("选择失败" + e.getMessage(), null);
        }
    }


    /**
     *上传作答答案

     * @return
     */
    @PostMapping("/uploadAnswers")
    @ApiOperation("上传作答结果")

    public Result<UploadAnswerResponse> uploadAnswers(@RequestBody UploadAnswerRequest request) {
        try {
            String paperId = request.getPaperId();
            List<String> selectedOptions = request.getSelectedOptions();
            List<String> questionIds = questionService.findQuestionIdsByPaperId(paperId);

            List<AnswerResult> correctionResults = new ArrayList<>();
            int totalScore = 0;

            for (int i = 0; i < questionIds.size(); i++) {
                String questionId = questionIds.get(i);
                String selectedOption = selectedOptions.get(i);
                if(selectedOption == null)
                    selectedOption = "EMPTY";
                String correctOption = questionService.findCorrectOptionByQuestionId(questionId);

                boolean correct = selectedOption.equals(correctOption);

                if (correct) {
                    totalScore += 5;
                }
                AnswerResult correctionResult = AnswerResult.builder()
                        .correct(correct)
                        .correctOption(correctOption)
                        .build();

                correctionResults.add(correctionResult);
            }
            UploadAnswerResponse uploadAnswerResponse = new UploadAnswerResponse();
            uploadAnswerResponse.setTotalScore(totalScore);
            uploadAnswerResponse.setCorrectionResults(correctionResults);


            return Result.success("批改成功", uploadAnswerResponse);
        } catch (Exception e) {
            return Result.fail("批改失败,请正确完成所有题目" + e.getMessage(), null);
        }
    }



    /**
     * 显示试卷
     * @return
     */
    @GetMapping("/showPaper")
    @ApiOperation("显示试卷")
    public Result<List<Map<String,String>>> showPaper() {
        try {
            List<TestPaperBriefEntity> res = testPaperService.findAllTestPaper();
            List<Map<String, String>> paperList = new ArrayList<>();
            for (TestPaperBriefEntity paper : res) {
                Map<String, String> paperInfo = new HashMap<>();
                paperInfo.put("headline", paper.getHeadline());
                paperInfo.put("paperId", String.valueOf(paper.getPaperId()));
                paperList.add(paperInfo);
            }
            if (res.isEmpty()) {
                return Result.fail("没有找到试卷", Collections.emptyList());
            } else {
                return Result.success("查询成功", paperList);
            }
        } catch (Exception e) {
            return Result.fail("显示试卷失败" + e.getMessage(), null);
        }
    }
}